import Worker from './flood.worker.js';

/**
 * 泛洪算法
 * @param {*} canvas 目标画布（仅作为处理对象）
 * @param {*} showCanvas 展示画布（仅作为输出画布） 
 * @param {*} startX 起始值X 默认值为0
 * @param {*} startY 起始值Y 默认值为0
 * @param {*} color 给定的需要判断的颜色值
 * @param {*} range 容错大小
 */

export default function cutoutFlood(canvas, showCanvas, range = 0.1 , callback ,bgColor, startX = 0, startY = 0, color) {
    let context = canvas.getContext('2d');   // 处理画布
    let showCtx = showCanvas.getContext('2d');   // 展示画布
    let imageInfo = context.getImageData(0, 0, canvas.width, canvas.height); // 获取目标图像image信息
    let pixiArr = imageInfo.data; // 拿到图像颜色数据
    color = color || context.getImageData(startX,startY,1,1).data; // 如果没有默认值，则选择泛洪坐标点的颜色值
    let similarPoint = [];
    let edgeLinePoint = [];

    let stack = [];  // 堆栈法，防治泛洪时发生溢出
    let {width,height} = canvas;
    let worker = new Worker();
    worker.postMessage({
        pixiArr,
        color,
        similarPoint,
        edgeLinePoint,
        stack,
        startX,
        startY,
        width,
        height,
        range
    });
    worker.onmessage = function(e) {
        // 处理结果 e.data.pixiArr
        let { color,similarPoint,edgeLinePoint } = e.data;
        let imageData = new ImageData(new Uint8ClampedArray(e.data.pixiArr),imageInfo.width,imageInfo.height)
        showCtx.putImageData(imageData, 0, 0);
        if(bgColor){
            context.globalCompositeOperation = "destination-over"
            context.fillStyle = `rgb( ${bgColor[0]},${bgColor[1]},${bgColor[2]})`;
            context.fillRect(0, 0, canvas.width, canvas.height);
        }
        callback({ color,imageData,similarPoint,edgeLinePoint })
        worker.terminate();
    }
}

